// -----------------------------------------------------------------------
//  <copyright file="SequenceSlaveDatabaseSelector.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2022 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2022-11-08 21:57</last-date>
// -----------------------------------------------------------------------

using DaprPlus.EntityFrameworkCore.Properties;


namespace DaprPlus.EntityFrameworkCore;

/// <summary>
/// 顺序从数据库选择器
/// </summary>
public class SequenceSlaveDatabaseSelector : ISlaveDatabaseSelector
{
    private static readonly object LockObj = new object();
    private int _sequenceIndex;
    private readonly ILogger _logger;

    /// <summary>
    /// 初始化一个<see cref="SequenceSlaveDatabaseSelector"/>类型的新实例
    /// </summary>
    public SequenceSlaveDatabaseSelector(IServiceProvider provider)
    {
        _logger = provider.GetLogger(this);
    }

    /// <summary>
    /// 获取 名称
    /// </summary>
    public string Name => "Sequence";

    /// <summary>
    /// 从所有从数据库中选择一个
    /// </summary>
    public SlaveDatabaseOptions Select(SlaveDatabaseOptions[] slaves)
    {
        Check.NotNullOrEmpty(slaves, nameof(slaves));
        
        lock (LockObj)
        {
            if (_sequenceIndex > slaves.Length - 1)
            {
                _sequenceIndex = 0;
            }

            var slave = slaves[_sequenceIndex];
            _logger.LogInformation(ResEFCore.Format_Entity_SelectSlave_Sequence, slave.Name, _sequenceIndex);
            _sequenceIndex++;

            return slave;
        }
    }
}
